<?php
/**
 * @package LaravelBoot
 *
 * @internal
 *
 * @author mawenpei
 * @date 2019/3/13 13:47
 * @version
 */
namespace Modules\Admin\Main\Controllers;

use App\Http\Controllers\Controller;
use App\Models\MobileRechargeOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Models\MobileRechargeTask;
use App\Models\User;

class MobileRechargeOrderController extends Controller
{
    public function index()
    {
        return view('main::mobile_recharge_order', \Request::all());
    }

    public function direct()
    {
        return view('main::mobile_recharge_direct_order', \Request::all());
    }

    public function all(Request $request)
    {
        $limit  = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $type   = $request->input('type', 1);
        $field_type = $request->input('field_type');
        $keyword = $request->input('keyword');
        $datetime = $request->input('datetime');
        $status = $request->input('status');

        $channel  = $request->input('channel','all');//渠道
        $recharge = $request->input('recharge','all');//套餐
        $market   = $request->input('market','all');
        $platform = $request->input('platform','all');

        $query = MobileRechargeOrder::query();

        $userQuery = (new User())->query();

        if($platform !== 'all'){
            $userQuery = $userQuery->where('app_platform',$platform);
        }

        if($market !== 'all'){
            $userQuery = $userQuery->where('app_channel',$market);
        }


        if($channel !== 'all'){
            $parent_id = (new User())->query()->where('open_code',$channel)->value('id');
            $userQuery = $userQuery->where('parent_id',$parent_id);

        }

        $user_ids = $userQuery->pluck('id');



        if($user_ids){
            $query = $query->whereIn('user_id',$user_ids->toArray());
        }else{
            $query = $query->where('user_id',-1);
        }

        if($type !== 'all'){
            $query = $query->where('type', $type);
        }

        if($field_type && !empty($keyword)){
            if($field_type == 'user_id'){
                $query = $query->where('user_id',$keyword);
            }
            if($field_type == 'mobile'){
                $query = $query->where('mobile',$keyword);
            }
        }

        if($datetime){
            if(isset($datetime[0])){
                $start_time = strtotime($datetime[0]);
                $datetime[0] = date('Y-m-d 00:00:00',$start_time);
                $query = $query->where('created_at','>=',$datetime[0]);
            }
            if(isset($datetime[1])){
                $end_time = strtotime($datetime[1]);
                $datetime[1] = date('Y-m-d 23:59:59',$end_time);
                $query = $query->where('created_at','<=',$datetime[1]);
            }

        }

        $query = $query->where('status', '>', 0);

        $data['total'] = $query->count();
        $data['total_recharge_amount'] = $query->sum('recharge_amount');
        $data['total_pay_amount'] = $query->sum('pay_amount');
        $res           = $query->take($limit)->skip($offset)->orderBy('id', 'desc')
            ->with(['user'])
            ->get();

        $data['items'] = [];
        foreach ($res as $item) {
            $_item = $item->toArray();
            $_item['mobile_en'] = encrypt($_item['mobile']);
//            $_item['mobile'] = convert_mobile($_item['mobile']);
            $data['items'][] = $_item;
        }

        return success($data);
    }

    public function failTask()
    {
        return view('main::recharge_task_fail', \Request::all());
    }

    public function task(Request $request)
    {
        $limit = $request->input('limit', 10);
        $offset = $request->input('offset', 0);
        $orderId = $request->input('order_id');
        $type = $request->input('type');

        $where = function($q) use ($orderId, $type) {
            if ($orderId) {
                $q->where('recharge_order_id', $orderId);
            }
            // 0待充值，1请求充值成功，2请求充值失败，4充值失败，9充值成功
            if ($type == 2) {
                $q->whereIn('status', [2, 4]);
            }
        };

        $data['total'] = MobileRechargeTask::where($where)->count();
        $res = MobileRechargeTask::where($where)
            ->take($limit)
            ->skip($offset)
            ->orderBy('pay_at', 'asc')->get();

        $data['items'] = [];
        foreach ($res as $item) {
            $_item = $item->toArray();

            $data['items'][] = $_item;
        }

//        foreach ($data['items'] as &$item) {
//            if ($item['result']) {
//                $item['result'] = json_decode($item['result'], true);
//            }
//        }

        return success($data);
    }

    /**
     * 拨打充值电话
     *
     * @author yls
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function call(Request $request)
    {
        $orderId = $request->get('order_id', 0);
        if (empty($orderId)) {
            return fail(400, '找不到数据');
        }

        $order = MobileRechargeOrder::query()->where('id', $orderId)->first();
        if (empty($order)) {
            return fail(400, '找不到数据');
        }

        if (empty($order->mobile)) {
            return fail(400, '手机号码不存在');
        }

        $res = $this->hollycrmCall($order->mobile);

        return $res ? success($res) : fail(400, '拨号失败');
    }
}